<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第1章-Spring源码纵览 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，Spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Spring源码纵览">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第1章-Spring源码纵览">
<meta property="og:url" content="https://imlql.cn/post/599156d.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="Spring源码纵览">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2021-12-06T15:21:58.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.049Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/599156d"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第1章-Spring源码纵览',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第1章-Spring源码纵览</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T15:21:58.000Z" title="发表于 2021-12-06 23:21:58">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.049Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>39分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="必读"><a href="#必读" class="headerlink" title="必读"></a>必读</h1><ol>
<li>源码是循循渐进的，前面我会省略中间很多目前不需要深入的代码，所以会看起来代码比较少。省略的地方我会打上这样的标识</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// ...      </span></span><br><span class="line">或者</span><br><span class="line"><span class="comment">// ......</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>如果没打也不代表我没省略，可能是忘记了，不要看懵了。</li>
</ol>
<h1 id="第1章-Spring源码纵览"><a href="#第1章-Spring源码纵览" class="headerlink" title="第1章-Spring源码纵览"></a>第1章-Spring源码纵览</h1><h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>Spring源码纵览这一节，主要是先了解下Spring的一些核心东西，所以前后可能关联不是特别深，跳跃性比较大，往后看就行。</p>
<h2 id="简单的继承关系图"><a href="#简单的继承关系图" class="headerlink" title="简单的继承关系图"></a>简单的继承关系图</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210926195844253.png" />

<ul>
<li><p><strong>蓝色实线箭头</strong>是指继承关系</p>
</li>
<li><p><strong>绿色虚线箭头</strong>是指接口实现关系</p>
</li>
<li><p><strong>绿色虚线箭头</strong>是指接口继承关系</p>
</li>
<li><p>注解版使用AnnotationConfigApplicationContext</p>
</li>
<li><p>XML版使用ClassPathXmlApplicationContext</p>
</li>
</ul>
<h2 id="Spring框架整体流程"><a href="#Spring框架整体流程" class="headerlink" title="Spring框架整体流程"></a>Spring框架整体流程</h2><ol>
<li>不管是用XML还是注解也好，最终形成一份组件或者功能的配置清单。</li>
<li>Spring用Resource来表示所有的资源</li>
<li>这些资源被ResourceLoader加载然后交给BeanDefinitionReader解析成BeanDefinition（Bean的定义信息）。BeanDefinition就是一个对象的图纸，模板。</li>
<li>然后将这些BeanDefinition放入到BeanDefinitionRegistry（其实就是一个Map）里，等待以后使用。</li>
<li>最后经过漫长的过程，根据BeanDefinition创建一个个的对象。</li>
</ol>
<h2 id="核心组件接口分析"><a href="#核心组件接口分析" class="headerlink" title="核心组件接口分析"></a>核心组件接口分析</h2><p><strong>基础接口</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Resource+ResourceLoader </span><br><span class="line">BeanFactory</span><br><span class="line">BeanDefinition</span><br><span class="line">BeanDefinitionReader</span><br><span class="line">BeanDefinitionRegistry</span><br><span class="line">ApplicationContext</span><br><span class="line">Aware</span><br></pre></td></tr></table></figure>

<p><strong>生命周期-后置处理器</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">BeanFactoryPostProcessor</span><br><span class="line">InitializingBean</span><br><span class="line">BeanPostProcessor</span><br></pre></td></tr></table></figure>



<h3 id="Resource资源"><a href="#Resource资源" class="headerlink" title="Resource资源"></a>Resource资源</h3><h4 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h4><p>快捷键：ctrl+F12 看类的方法</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210926232957909.png"/>

<h4 id="实现类"><a href="#实现类" class="headerlink" title="实现类"></a>实现类</h4><p>快捷键：ctrl+h 查看接口实现类</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210926233308861.png"/>



<ol>
<li><p>ContextResource：表示可以拿Web环境的资源</p>
</li>
<li><p>HttpResource：可以从网络中拿到资源</p>
</li>
<li><p>WritableResource：</p>
<ol>
<li>FileSystemResource：可以从文件系统拿到资源</li>
<li>FileUrlResource：URL就是统一资源定位符的意思；URL可以定位到网络，磁盘，等任何你想定位到的位置；表示Spring几乎可以从任何地方拿到资源。</li>
</ol>
</li>
<li><p>AbstractResource</p>
<ol>
<li>ByteArrayResource：从byte数组拿到资源</li>
<li>InputStreamResource：从Input流中拿到资源</li>
</ol>
</li>
<li><p>综合来说Spring几乎可以从任何地方拿到资源。</p>
</li>
</ol>
<h3 id="ResourceLoader资源加载器"><a href="#ResourceLoader资源加载器" class="headerlink" title="ResourceLoader资源加载器"></a>ResourceLoader资源加载器</h3><p>此类的源码开头有这样一句话，Strategy interface（策略接口），显然用到了策略模式。策略体现在哪个地方，我们下面再说。</p>
<blockquote>
<p>Strategy interface for loading resources (e.g., class path or file systemresources)</p>
</blockquote>
<h4 id="方法-1"><a href="#方法-1" class="headerlink" title="方法"></a>方法</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Strategy interface（策略接口） for loading resources (e.g., class path or file system</span></span><br><span class="line"><span class="comment"> * resources). An &#123;<span class="doctag">@link</span> org.springframework.context.ApplicationContext&#125;</span></span><br><span class="line"><span class="comment"> * is required to provide this functionality plus extended</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.core.io.support.ResourcePatternResolver&#125; support.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;&#123;<span class="doctag">@link</span> DefaultResourceLoader&#125; is a standalone implementation that is</span></span><br><span class="line"><span class="comment"> * usable outside an ApplicationContext and is also used by &#123;<span class="doctag">@link</span> ResourceEditor&#125;.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Bean properties of type &#123;<span class="doctag">@code</span> Resource&#125; and &#123;<span class="doctag">@code</span> Resource[]&#125; can be populated</span></span><br><span class="line"><span class="comment"> * from Strings when running in an ApplicationContext, using the particular</span></span><br><span class="line"><span class="comment"> * context&#x27;s resource loading strategy.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 10.03.2004</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> Resource</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.core.io.support.ResourcePatternResolver</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.ApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.ResourceLoaderAware</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ResourceLoader</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/** Pseudo URL prefix for loading from the class path: &quot;classpath:&quot;. */</span></span><br><span class="line">   String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Return a &#123;<span class="doctag">@code</span> Resource&#125; handle for the specified resource location.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;The handle should always be a reusable resource descriptor,</span></span><br><span class="line"><span class="comment">    * allowing for multiple &#123;<span class="doctag">@link</span> Resource#getInputStream()&#125; calls.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;&lt;ul&gt;</span></span><br><span class="line"><span class="comment">    * &lt;li&gt;Must support fully qualified URLs, e.g. &quot;file:C:/test.dat&quot;.</span></span><br><span class="line"><span class="comment">    * &lt;li&gt;Must support classpath pseudo-URLs, e.g. &quot;classpath:test.dat&quot;.</span></span><br><span class="line"><span class="comment">    * &lt;li&gt;Should support relative file paths, e.g. &quot;WEB-INF/test.dat&quot;.</span></span><br><span class="line"><span class="comment">    * (This will be implementation-specific, typically provided by an</span></span><br><span class="line"><span class="comment">    * ApplicationContext implementation.)</span></span><br><span class="line"><span class="comment">    * &lt;/ul&gt;</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;Note that a &#123;<span class="doctag">@code</span> Resource&#125; handle does not imply an existing resource;</span></span><br><span class="line"><span class="comment">    * you need to invoke &#123;<span class="doctag">@link</span> Resource#exists&#125; to check for existence.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> location the resource location</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> a corresponding &#123;<span class="doctag">@code</span> Resource&#125; handle (never &#123;<span class="doctag">@code</span> null&#125;)</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> #CLASSPATH_URL_PREFIX</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> Resource#exists()</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> Resource#getInputStream()</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function">Resource <span class="title">getResource</span><span class="params">(String location)</span></span>; <span class="comment">//这个是最关键的</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * Expose the &#123;<span class="doctag">@link</span> ClassLoader&#125; used by this &#123;<span class="doctag">@code</span> ResourceLoader&#125;.</span></span><br><span class="line"><span class="comment">    * &lt;p&gt;Clients which need to access the &#123;<span class="doctag">@code</span> ClassLoader&#125; directly can do so</span></span><br><span class="line"><span class="comment">    * in a uniform manner with the &#123;<span class="doctag">@code</span> ResourceLoader&#125;, rather than relying</span></span><br><span class="line"><span class="comment">    * on the thread context &#123;<span class="doctag">@code</span> ClassLoader&#125;.</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span> the &#123;<span class="doctag">@code</span> ClassLoader&#125;</span></span><br><span class="line"><span class="comment">    * (only &#123;<span class="doctag">@code</span> null&#125; if even the system &#123;<span class="doctag">@code</span> ClassLoader&#125; isn&#x27;t accessible)</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> org.springframework.util.ClassUtils#getDefaultClassLoader()</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@see</span> org.springframework.util.ClassUtils#forName(String, ClassLoader)</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function">ClassLoader <span class="title">getClassLoader</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="实现类-1"><a href="#实现类-1" class="headerlink" title="实现类"></a>实现类</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210926234527992.png" />



<ol>
<li>DefaultResourceLoader：默认资源加载器<ol>
<li>ClassRelativeResourceLoader：能读取类路径相对路径</li>
<li>FileSystemResourceLoader：能读取文件系统的</li>
<li>ServletContextResourceLoader：能读取web环境的</li>
</ol>
</li>
</ol>
<h3 id="BeanFactory-Bean工厂"><a href="#BeanFactory-Bean工厂" class="headerlink" title="BeanFactory-Bean工厂"></a>BeanFactory-Bean工厂</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * The root interface for accessing a Spring bean container.</span></span><br><span class="line"><span class="comment"> * 根接口，整个访问容器的入口</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This is the basic client view of a bean container;</span></span><br><span class="line"><span class="comment"> * further interfaces such as &#123;<span class="doctag">@link</span> ListableBeanFactory&#125; and</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.beans.factory.config.ConfigurableBeanFactory&#125;</span></span><br><span class="line"><span class="comment"> * are available for specific purposes.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This interface is implemented by objects that hold a number of bean definitions,</span></span><br><span class="line"><span class="comment"> * 保存很多的BeanDefinition信息,都有一个唯一的名字</span></span><br><span class="line"><span class="comment"> * each uniquely identified by a String name. Depending on the bean definition,</span></span><br><span class="line"><span class="comment"> * the factory will return either an independent instance of a contained object</span></span><br><span class="line"><span class="comment"> * (the Prototype design pattern【原型模式】), or a single shared instance (a superior</span></span><br><span class="line"><span class="comment"> * alternative to the Singleton design pattern【单例设计模式】, in which the instance is a</span></span><br><span class="line"><span class="comment"> * singleton in the scope of the factory). Which type of instance will be returned</span></span><br><span class="line"><span class="comment"> * depends on the bean factory configuration: the API is the same. Since Spring</span></span><br><span class="line"><span class="comment"> * 2.0, further scopes are available depending on the concrete application</span></span><br><span class="line"><span class="comment"> * context (e.g. &quot;request&quot; and &quot;session&quot; scopes in a web environment).</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanFactory</span> </span>&#123;</span><br><span class="line">    <span class="comment">//省略...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>源码分析小技巧：看源码时，我们可以先看一个类的接口继承关系，因为接口就是规范，大部分开源框架源码都是遵守这一规范的。</p>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927103844753.png" />



<ol>
<li>BeanFactory<ol>
<li>HierarchicalBeanFactory：定义父子工厂（父子容器）</li>
<li>ListableBeanFacotory：实现是DefaultListableBeanFactory，保存了ioc容器中的核心信息。</li>
<li>AutowireCapableBeanFactory：提供自动装配能力</li>
<li>AnnotationApplicationContext：组合了<strong>一个总的注册中心</strong>（DefaultListableBeanFactory），它有自动装配能力。</li>
</ol>
</li>
</ol>
<h4 id="AbstractApplicationContext"><a href="#AbstractApplicationContext" class="headerlink" title="AbstractApplicationContext"></a>AbstractApplicationContext</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927104922679.png" />

<p>环境类的意思就是谁持有这个策略；这里就解释了上文说ResourceLoader是环境类接口</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 策略模式的环境类</span></span><br><span class="line"><span class="keyword">private</span> ResourcePatternResolver resourcePatternResolver;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AbstractApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.resourcePatternResolver = getResourcePatternResolver();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="GenericApplicationContext"><a href="#GenericApplicationContext" class="headerlink" title="GenericApplicationContext"></a>GenericApplicationContext</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927105641446.png"/>

<p>这里组合了DefaultListableBeanFactory</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GenericApplicationContext</span> <span class="keyword">extends</span> <span class="title">AbstractApplicationContext</span> <span class="keyword">implements</span> <span class="title">BeanDefinitionRegistry</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> DefaultListableBeanFactory beanFactory;</span><br><span class="line">   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="DefaultListableBeanFactory"><a href="#DefaultListableBeanFactory" class="headerlink" title="DefaultListableBeanFactory"></a>DefaultListableBeanFactory</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultListableBeanFactory</span> <span class="keyword">extends</span> <span class="title">AbstractAutowireCapableBeanFactory</span></span></span><br><span class="line"><span class="class">      <span class="keyword">implements</span> <span class="title">ConfigurableListableBeanFactory</span>, <span class="title">BeanDefinitionRegistry</span>, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/** Map from serialized id to factory instance. */</span></span><br><span class="line"></span><br><span class="line">   <span class="comment">//组合模式,Spring里面可以有很多工厂，每一个工厂有自己的ID，好处就是工厂之间的bean可以隔离起来，但是用的很少</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Map&lt;String, Reference&lt;DefaultListableBeanFactory&gt;&gt; serializableFactories =</span><br><span class="line">         <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;(<span class="number">8</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**如果容器中有Map&lt;Class, Object[]/String[] &gt;&lt;/&gt; Map of bean definition objects, keyed by bean name. */</span></span><br><span class="line">   <span class="comment">//所有BeanDefinition信息按照名字对应BeanDefinition关系都保存好了。</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, BeanDefinition&gt; beanDefinitionMap = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;(<span class="number">256</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/** Map of singleton-only bean names, keyed by dependency type. */</span></span><br><span class="line">   <span class="comment">//Spring中按照类型得到组件的一个底层池</span></span><br><span class="line">    <span class="comment">//车的图纸和车的关系。这里只保存图纸(也就是类信息)，对象存哪里呢？往后看</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;Class&lt;?&gt;, String[]&gt; singletonBeanNamesByType = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;(<span class="number">64</span>);</span><br><span class="line"></span><br><span class="line">   <span class="comment">/** List of bean definition names, in registration order. */</span></span><br><span class="line">   <span class="comment">//保存所有BeanDefinition的名字。</span></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">volatile</span> List&lt;String&gt; beanDefinitionNames = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">256</span>);</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927110806180.png"  />

<ol>
<li>BeanDefinitionRegistry：Bean定义信息注册中心</li>
<li>SimpleAliasRegistry：别名注册中心</li>
<li>SingletonBeanRegistry：单实例注册中心</li>
<li>BeanFactory：Bean工厂</li>
<li>AutowireCapableBeanFactory：有自动装配能力的Bean工厂</li>
<li>DefaultListableBeanFactory：可以理解为拥有上面所有注册中心功能的一个总的注册中心</li>
<li>GenericApplicationContext有一个我们常用的实现类AnnotationConfigApplicationContext，就是注解版的IOC容器</li>
<li>虽然我们的IOC容器和DefaultListableBeanFactory没有继承的父子关系，但是却组合了DefaultListableBeanFactory，拥有了它的全部功能。</li>
<li>DefaultListableBeanFactory在Spring中扮演着至关重要的角色。</li>
</ol>
<blockquote>
<ol>
<li>DefaultListableBeanFactory保存了所有对象（bean）的图纸（也就是类模板），并没有真正存对象。</li>
<li>我们这里猜想一下，Spring底层真正存Bean的地方用的是哪个数据结构呢？是List，还是Set，还是Map。咱们稍微想一下就知道肯定是Map，并且Key是beanName，value是真正的Bean。如果不是Map的话，如何通过BeanName拿到对应的Bean呢？</li>
<li>其实就是上面的那个beanDefinitionMap</li>
</ol>
</blockquote>
<h3 id="注册BeanDefinition-1"><a href="#注册BeanDefinition-1" class="headerlink" title="注册BeanDefinition-1"></a>注册BeanDefinition-1</h3><h4 id="流程图-BeanDefinition注册流程"><a href="#流程图-BeanDefinition注册流程" class="headerlink" title="流程图-BeanDefinition注册流程"></a>流程图-BeanDefinition注册流程</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/Spring%E6%BA%90%E7%A0%81-BeanDefinition%E6%B3%A8%E5%86%8C%E6%B5%81%E7%A8%8B.png">

<ul>
<li>我们要看BeanDefinition是何时被放入到beanDefinitionMap，只需要在DefaultListableBeanFactory用到<code>beanDefinitionMap.put()</code>的地方打个断点。</li>
<li>我们在DefaultListableBeanFactory里搜索，发现了registerBeanDefinition（注册Bean定义信息）这个方法名很像我们要找的东西，再看里面的代码，果然有<code>beanDefinitionMap.put()</code>这串代码，我们试着在这里打个断点</li>
<li>然后启动下面的测试类</li>
<li>上面就是我们看一个框架源码，可以往哪些方向去猜测。</li>
</ul>
<h4 id="MainTest测试类"><a href="#MainTest测试类" class="headerlink" title="MainTest测试类"></a>MainTest测试类</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">      ClassPathXmlApplicationContext context = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;beans.xml&quot;</span>);</span><br><span class="line">      Person bean = context.getBean(Person.class);</span><br><span class="line">      System.out.println(bean);</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927142317864.png" />

<blockquote>
<p>调用栈的调用顺序已经非常清楚了，可以把图放大一点看，下面只说一些必要的信息。</p>
</blockquote>
<ol>
<li><p><code>new ClassPathXmlApplicationContext(&quot;beans.xml&quot;)</code>这一步开始就要刷新容器了</p>
</li>
<li><p>调用<code>AbstractApplicationContext#refresh()</code>这个方法，<code>refresh()</code>方法是容器刷新的几大步所在地</p>
</li>
</ol>
<h4 id="AbstractApplicationContext-refresh-容器刷新"><a href="#AbstractApplicationContext-refresh-容器刷新" class="headerlink" title="AbstractApplicationContext#refresh()容器刷新"></a>AbstractApplicationContext#refresh()容器刷新</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">      StartupStep contextRefresh = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.refresh&quot;</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Prepare this context for refreshing.</span></span><br><span class="line">      prepareRefresh();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">      <span class="comment">// BeanFactory第一次开始创建的时候,有xml解析逻辑。</span></span><br><span class="line">      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Prepare the bean factory for use in this context.</span></span><br><span class="line">      prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// ......</span></span><br><span class="line">         <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">         <span class="comment">//完成 BeanFactory 初始化</span></span><br><span class="line">         finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Last step: publish corresponding event.</span></span><br><span class="line">         finishRefresh();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// ......</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="AbstractApplicationContext-obtainFreshBeanFactory-第一次开始创建BeanFactory"><a href="#AbstractApplicationContext-obtainFreshBeanFactory-第一次开始创建BeanFactory" class="headerlink" title="AbstractApplicationContext#obtainFreshBeanFactory()第一次开始创建BeanFactory"></a>AbstractApplicationContext#obtainFreshBeanFactory()第一次开始创建BeanFactory</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> ConfigurableListableBeanFactory <span class="title">obtainFreshBeanFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   refreshBeanFactory(); <span class="comment">//刷新整个BeanFactory</span></span><br><span class="line">   <span class="keyword">return</span> getBeanFactory();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="AbstractRefreshableApplicationContext-refreshBeanFactory-刷新整个BeanFactory"><a href="#AbstractRefreshableApplicationContext-refreshBeanFactory-刷新整个BeanFactory" class="headerlink" title="AbstractRefreshableApplicationContext#refreshBeanFactory()刷新整个BeanFactory"></a>AbstractRefreshableApplicationContext#refreshBeanFactory()刷新整个BeanFactory</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">refreshBeanFactory</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (hasBeanFactory()) &#123;</span><br><span class="line">      destroyBeans();</span><br><span class="line">      closeBeanFactory();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      DefaultListableBeanFactory beanFactory = createBeanFactory(); <span class="comment">//创建保存所有Bean定义信息的档案馆</span></span><br><span class="line">      beanFactory.setSerializationId(getId());</span><br><span class="line">      customizeBeanFactory(beanFactory);</span><br><span class="line">      loadBeanDefinitions(beanFactory); <span class="comment">//开始加载Bean定义信息</span></span><br><span class="line">      <span class="keyword">this</span>.beanFactory = beanFactory;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(<span class="string">&quot;I/O error parsing bean definition source for &quot;</span> + getDisplayName(), ex);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="AbstractXmlApplicationContext-loadBeanDefinitions-加载Bean定义信息"><a href="#AbstractXmlApplicationContext-loadBeanDefinitions-加载Bean定义信息" class="headerlink" title="AbstractXmlApplicationContext#loadBeanDefinitions()加载Bean定义信息"></a>AbstractXmlApplicationContext#loadBeanDefinitions()加载Bean定义信息</h4><p>下面就是一堆的loadBeanDefinitions调用，调用顺序就是我下面写的代码顺序。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   </span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">loadBeanDefinitions</span><span class="params">(DefaultListableBeanFactory beanFactory)</span> <span class="keyword">throws</span> BeansException, IOException </span>&#123;</span><br><span class="line">      <span class="comment">// Create a new XmlBeanDefinitionReader for the given BeanFactory. 准备读取xml内容的读取器</span></span><br><span class="line">      XmlBeanDefinitionReader beanDefinitionReader = <span class="keyword">new</span> XmlBeanDefinitionReader(beanFactory);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Configure the bean definition reader with this context&#x27;s</span></span><br><span class="line">      <span class="comment">// resource loading environment.</span></span><br><span class="line">      beanDefinitionReader.setEnvironment(<span class="keyword">this</span>.getEnvironment());</span><br><span class="line">      beanDefinitionReader.setResourceLoader(<span class="keyword">this</span>); <span class="comment">//持有ioc容器的环境类</span></span><br><span class="line">      beanDefinitionReader.setEntityResolver(<span class="keyword">new</span> ResourceEntityResolver(<span class="keyword">this</span>));</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Allow a subclass to provide custom initialization of the reader,</span></span><br><span class="line">      <span class="comment">// then proceed with actually loading the bean definitions.</span></span><br><span class="line">      initBeanDefinitionReader(beanDefinitionReader);</span><br><span class="line">      loadBeanDefinitions(beanDefinitionReader);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">loadBeanDefinitions</span><span class="params">(XmlBeanDefinitionReader reader)</span> <span class="keyword">throws</span> BeansException, IOException </span>&#123;</span><br><span class="line">	Resource[] configResources = getConfigResources();</span><br><span class="line">	<span class="keyword">if</span> (configResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">		reader.loadBeanDefinitions(configResources);</span><br><span class="line">	&#125;</span><br><span class="line">	String[] configLocations = getConfigLocations(); <span class="comment">//可以一次传入很多配置文件</span></span><br><span class="line">	<span class="keyword">if</span> (configLocations != <span class="keyword">null</span>) &#123;</span><br><span class="line">		reader.loadBeanDefinitions(configLocations); <span class="comment">//读取文件</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h4 id="AbstractBeanDefinitionReader-loadBeanDefinitions"><a href="#AbstractBeanDefinitionReader-loadBeanDefinitions" class="headerlink" title="AbstractBeanDefinitionReader#loadBeanDefinitions()"></a>AbstractBeanDefinitionReader#loadBeanDefinitions()</h4><p>下面也是一堆的loadBeanDefinitions调用，调用顺序就是我下面写的代码顺序。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String... locations)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">       Assert.notNull(locations, <span class="string">&quot;Location array must not be null&quot;</span>);</span><br><span class="line">       <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">       <span class="keyword">for</span> (String location : locations) &#123; <span class="comment">//加载每一个配置文件里面的内容</span></span><br><span class="line">           count += loadBeanDefinitions(location);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> count;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span>  <span class="comment">//加载指定配置文件的所有内容</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String location)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">       <span class="keyword">return</span> loadBeanDefinitions(location, <span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(String location, <span class="meta">@Nullable</span> Set&lt;Resource&gt; actualResources)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">	ResourceLoader resourceLoader = getResourceLoader();</span><br><span class="line">	<span class="keyword">if</span> (resourceLoader == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">				<span class="string">&quot;Cannot load bean definitions from location [&quot;</span> + location + <span class="string">&quot;]: no ResourceLoader available&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (resourceLoader <span class="keyword">instanceof</span> ResourcePatternResolver) &#123;</span><br><span class="line">		<span class="comment">// Resource pattern matching available.</span></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); <span class="comment">//得到实体文件对应的资源</span></span><br><span class="line">			<span class="keyword">int</span> count = loadBeanDefinitions(resources);</span><br><span class="line">			<span class="keyword">if</span> (actualResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">				Collections.addAll(actualResources, resources);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">				logger.trace(<span class="string">&quot;Loaded &quot;</span> + count + <span class="string">&quot; bean definitions from location pattern [&quot;</span> + location + <span class="string">&quot;]&quot;</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> count;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">					<span class="string">&quot;Could not resolve bean definition resource pattern [&quot;</span> + location + <span class="string">&quot;]&quot;</span>, ex);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="comment">// Can only load single resources by absolute URL. 这里开始转换成我们前面说的Resource资源</span></span><br><span class="line">		Resource resource = resourceLoader.getResource(location);</span><br><span class="line">		<span class="keyword">int</span> count = loadBeanDefinitions(resource);</span><br><span class="line">		<span class="keyword">if</span> (actualResources != <span class="keyword">null</span>) &#123;</span><br><span class="line">			actualResources.add(resource);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">			logger.trace(<span class="string">&quot;Loaded &quot;</span> + count + <span class="string">&quot; bean definitions from location [&quot;</span> + location + <span class="string">&quot;]&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> count;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(Resource... resources)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">	Assert.notNull(resources, <span class="string">&quot;Resource array must not be null&quot;</span>);</span><br><span class="line">	<span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span> (Resource resource : resources) &#123;</span><br><span class="line">		count += loadBeanDefinitions(resource);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="XmlBeanDefinitionReader-loadBeanDefinitions"><a href="#XmlBeanDefinitionReader-loadBeanDefinitions" class="headerlink" title="XmlBeanDefinitionReader#loadBeanDefinitions()"></a>XmlBeanDefinitionReader#loadBeanDefinitions()</h4><p>又是一堆loadBeanDefinitions调用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">      <span class="comment">// 这里是个适配器模式 对接 InputStreamSource 和 Resource 或者说是个装饰器模式也可以</span></span><br><span class="line">      <span class="keyword">return</span> loadBeanDefinitions(<span class="keyword">new</span> EncodedResource(resource));</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">loadBeanDefinitions</span><span class="params">(EncodedResource encodedResource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">	Assert.notNull(encodedResource, <span class="string">&quot;EncodedResource must not be null&quot;</span>);</span><br><span class="line">	<span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">		logger.trace(<span class="string">&quot;Loading XML bean definitions from &quot;</span> + encodedResource);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	Set&lt;EncodedResource&gt; currentResources = <span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.get();</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> (!currentResources.add(encodedResource)) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">				<span class="string">&quot;Detected cyclic loading of &quot;</span> + encodedResource + <span class="string">&quot; - check your import definitions!&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> (InputStream inputStream = encodedResource.getResource().getInputStream()) &#123;</span><br><span class="line">		InputSource inputSource = <span class="keyword">new</span> InputSource(inputStream);</span><br><span class="line">		<span class="keyword">if</span> (encodedResource.getEncoding() != <span class="keyword">null</span>) &#123;</span><br><span class="line">			inputSource.setEncoding(encodedResource.getEncoding());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> doLoadBeanDefinitions(inputSource, encodedResource.getResource());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(</span><br><span class="line">				<span class="string">&quot;IOException parsing XML document from &quot;</span> + encodedResource.getResource(), ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">		currentResources.remove(encodedResource);</span><br><span class="line">		<span class="keyword">if</span> (currentResources.isEmpty()) &#123;</span><br><span class="line">			<span class="keyword">this</span>.resourcesCurrentlyBeingLoaded.remove();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">doLoadBeanDefinitions</span><span class="params">(InputSource inputSource, Resource resource)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		Document doc = doLoadDocument(inputSource, resource); <span class="comment">//利用dom解析工具把xml变成Document</span></span><br><span class="line">		<span class="keyword">int</span> count = registerBeanDefinitions(doc, resource); <span class="comment">//开始注册了</span></span><br><span class="line">		<span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">			logger.debug(<span class="string">&quot;Loaded &quot;</span> + count + <span class="string">&quot; bean definitions from &quot;</span> + resource);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> count;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> ex;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (SAXParseException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> XmlBeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">				<span class="string">&quot;Line &quot;</span> + ex.getLineNumber() + <span class="string">&quot; in XML document from &quot;</span> + resource + <span class="string">&quot; is invalid&quot;</span>, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (SAXException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> XmlBeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">				<span class="string">&quot;XML document from &quot;</span> + resource + <span class="string">&quot; is invalid&quot;</span>, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (ParserConfigurationException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">				<span class="string">&quot;Parser configuration exception parsing XML from &quot;</span> + resource, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">				<span class="string">&quot;IOException parsing XML document from &quot;</span> + resource, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(resource.getDescription(),</span><br><span class="line">				<span class="string">&quot;Unexpected exception parsing XML document from &quot;</span> + resource, ex);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, Resource resource)</span> <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line">	BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();</span><br><span class="line">	<span class="keyword">int</span> countBefore = getRegistry().getBeanDefinitionCount();</span><br><span class="line">	documentReader.registerBeanDefinitions(doc, createReaderContext(resource));</span><br><span class="line">	<span class="keyword">return</span> getRegistry().getBeanDefinitionCount() - countBefore;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="DefaultBeanDefinitionDocumentReader-registerBeanDefinitions-注册Bean定义信息"><a href="#DefaultBeanDefinitionDocumentReader-registerBeanDefinitions-注册Bean定义信息" class="headerlink" title="DefaultBeanDefinitionDocumentReader#registerBeanDefinitions()注册Bean定义信息"></a>DefaultBeanDefinitionDocumentReader#registerBeanDefinitions()注册Bean定义信息</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(Document doc, XmlReaderContext readerContext)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.readerContext = readerContext;</span><br><span class="line">      doRegisterBeanDefinitions(doc.getDocumentElement());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doRegisterBeanDefinitions</span><span class="params">(Element root)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// this behavior emulates a stack of delegates without actually necessitating one.</span></span><br><span class="line">	BeanDefinitionParserDelegate parent = <span class="keyword">this</span>.delegate; <span class="comment">//由这个类进行最终解析</span></span><br><span class="line">	<span class="keyword">this</span>.delegate = createDelegate(getReaderContext(), root, parent);</span><br><span class="line">	</span><br><span class="line">       <span class="comment">//省略不重要的代码......</span></span><br><span class="line">	preProcessXml(root);</span><br><span class="line">	parseBeanDefinitions(root, <span class="keyword">this</span>.delegate);</span><br><span class="line">	postProcessXml(root);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">this</span>.delegate = parent;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//省略不重要的代码......</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//最后经过一些列的document文档遍历解析，走到了下面这个方法</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processBeanDefinition</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</span><br><span class="line">	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); <span class="comment">//把当前标签解析完了，BeanDefinition和beanName都封装在了Holder中</span></span><br><span class="line">	<span class="keyword">if</span> (bdHolder != <span class="keyword">null</span>) &#123;</span><br><span class="line">		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// Register the final decorated instance.</span></span><br><span class="line">			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">			getReaderContext().error(<span class="string">&quot;Failed to register bean definition with name &#x27;&quot;</span> +</span><br><span class="line">					bdHolder.getBeanName() + <span class="string">&quot;&#x27;&quot;</span>, ele, ex);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// Send registration event.  //发送一个通知事件</span></span><br><span class="line">		getReaderContext().fireComponentRegistered(<span class="keyword">new</span> BeanComponentDefinition(bdHolder));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h4 id="BeanDefinitionReaderUtils-registerBeanDefinition"><a href="#BeanDefinitionReaderUtils-registerBeanDefinition" class="headerlink" title="BeanDefinitionReaderUtils#registerBeanDefinition()"></a>BeanDefinitionReaderUtils#registerBeanDefinition()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">registerBeanDefinition</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)</span></span></span><br><span class="line"><span class="function">      <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Register bean definition under primary name.</span></span><br><span class="line">   String beanName = definitionHolder.getBeanName();</span><br><span class="line">   registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Register aliases for bean name, if any. 别名</span></span><br><span class="line">   String[] aliases = definitionHolder.getAliases();</span><br><span class="line">   <span class="keyword">if</span> (aliases != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">for</span> (String alias : aliases) &#123;</span><br><span class="line">         registry.registerAlias(beanName, alias);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="DefaultListableBeanFactory-registerBeanDefinition"><a href="#DefaultListableBeanFactory-registerBeanDefinition" class="headerlink" title="DefaultListableBeanFactory#registerBeanDefinition()"></a>DefaultListableBeanFactory#registerBeanDefinition()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//终于走到了这最后一步</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinition</span><span class="params">(String beanName, BeanDefinition beanDefinition)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> BeanDefinitionStoreException </span>&#123;</span><br><span class="line"></span><br><span class="line">    Assert.hasText(beanName, <span class="string">&quot;Bean name must not be empty&quot;</span>);</span><br><span class="line">    Assert.notNull(beanDefinition, <span class="string">&quot;BeanDefinition must not be null&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (beanDefinition <span class="keyword">instanceof</span> AbstractBeanDefinition) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ((AbstractBeanDefinition) beanDefinition).validate();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (BeanDefinitionValidationException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,</span><br><span class="line">                    <span class="string">&quot;Validation of bean definition failed&quot;</span>, ex);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    BeanDefinition existingDefinition = <span class="keyword">this</span>.beanDefinitionMap.get(beanName);</span><br><span class="line">    <span class="comment">//先看beanDefinitionMap有没有，没有我才注册</span></span><br><span class="line">    <span class="keyword">if</span> (existingDefinition != <span class="keyword">null</span>) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//省略一系列目前来说不重要的判断......</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (hasBeanCreationStarted()) &#123;</span><br><span class="line">            <span class="comment">// Cannot modify startup-time collection elements anymore (for stable iteration)</span></span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>.beanDefinitionMap) &#123;</span><br><span class="line">                <span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition); <span class="comment">//注册进去了</span></span><br><span class="line">                List&lt;String&gt; updatedDefinitions = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="keyword">this</span>.beanDefinitionNames.size() + <span class="number">1</span>);</span><br><span class="line">                updatedDefinitions.addAll(<span class="keyword">this</span>.beanDefinitionNames);</span><br><span class="line">                updatedDefinitions.add(beanName);</span><br><span class="line">                <span class="keyword">this</span>.beanDefinitionNames = updatedDefinitions;</span><br><span class="line">                removeManualSingletonName(beanName);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Still in startup registration phase</span></span><br><span class="line">            <span class="keyword">this</span>.beanDefinitionMap.put(beanName, beanDefinition);</span><br><span class="line">            <span class="keyword">this</span>.beanDefinitionNames.add(beanName);</span><br><span class="line">            removeManualSingletonName(beanName);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.frozenBeanDefinitionNames = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (existingDefinition != <span class="keyword">null</span> || containsSingleton(beanName)) &#123;</span><br><span class="line">        resetBeanDefinition(beanName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (isConfigurationFrozen()) &#123;</span><br><span class="line">        clearByTypeCache();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="注册BeanDefinition-2"><a href="#注册BeanDefinition-2" class="headerlink" title="注册BeanDefinition-2"></a>注册BeanDefinition-2</h3><h4 id="Debug调用栈-1"><a href="#Debug调用栈-1" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h4><ul>
<li>还有一个debug的猜测方向，想要注册BeanDefinition肯定要new，我们可以直接在AbstractBeanDefinition这个抽象父类的构造函数打断点，我们不知道会走哪个构造函数，所以给三个构造函数都打断点。</li>
<li>下面就是打完断点之后，运行MainTest测试类后的调用栈</li>
</ul>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927172855410.png"/>



<blockquote>
<p>前面的调用栈都是一样的，从下面开始不一样</p>
</blockquote>
<h4 id="DefaultBeanDefinitionDocumentReader-processBeanDefinition"><a href="#DefaultBeanDefinitionDocumentReader-processBeanDefinition" class="headerlink" title="DefaultBeanDefinitionDocumentReader#processBeanDefinition()"></a>DefaultBeanDefinitionDocumentReader#processBeanDefinition()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processBeanDefinition</span><span class="params">(Element ele, BeanDefinitionParserDelegate delegate)</span> </span>&#123;</span><br><span class="line">   BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); <span class="comment">//把当前标签解析完了，BeanDefinition和beanName都封装在了Holder中</span></span><br><span class="line">   <span class="keyword">if</span> (bdHolder != <span class="keyword">null</span>) &#123;</span><br><span class="line">      bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">// Register the final decorated instance.</span></span><br><span class="line">         BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (BeanDefinitionStoreException ex) &#123;</span><br><span class="line">         getReaderContext().error(<span class="string">&quot;Failed to register bean definition with name &#x27;&quot;</span> +</span><br><span class="line">               bdHolder.getBeanName() + <span class="string">&quot;&#x27;&quot;</span>, ele, ex);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// Send registration event.  //发送一个通知事件</span></span><br><span class="line">      getReaderContext().fireComponentRegistered(<span class="keyword">new</span> BeanComponentDefinition(bdHolder));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="BeanDefinitionParserDelegate-parseBeanDefinitionElement"><a href="#BeanDefinitionParserDelegate-parseBeanDefinitionElement" class="headerlink" title="BeanDefinitionParserDelegate#parseBeanDefinitionElement()"></a>BeanDefinitionParserDelegate#parseBeanDefinitionElement()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ID_ATTRIBUTE = <span class="string">&quot;id&quot;</span>;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String NAME_ATTRIBUTE = <span class="string">&quot;name&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> BeanDefinitionHolder <span class="title">parseBeanDefinitionElement</span><span class="params">(Element ele, <span class="meta">@Nullable</span> BeanDefinition containingBean)</span> </span>&#123;</span><br><span class="line">      String id = ele.getAttribute(ID_ATTRIBUTE);</span><br><span class="line">      String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);</span><br><span class="line"></span><br><span class="line">      List&lt;String&gt; aliases = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      <span class="keyword">if</span> (StringUtils.hasLength(nameAttr)) &#123;</span><br><span class="line">         String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);</span><br><span class="line">         aliases.addAll(Arrays.asList(nameArr));</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      String beanName = id; <span class="comment">//为什么说id就是BeanName，Spring源码这里自己写的</span></span><br><span class="line">      <span class="keyword">if</span> (!StringUtils.hasText(beanName) &amp;&amp; !aliases.isEmpty()) &#123;</span><br><span class="line">         beanName = aliases.remove(<span class="number">0</span>);</span><br><span class="line">         <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(<span class="string">&quot;No XML &#x27;id&#x27; specified - using &#x27;&quot;</span> + beanName +</span><br><span class="line">                  <span class="string">&quot;&#x27; as bean name and &quot;</span> + aliases + <span class="string">&quot; as aliases&quot;</span>);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (containingBean == <span class="keyword">null</span>) &#123;</span><br><span class="line">         checkNameUniqueness(beanName, aliases, ele);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);</span><br><span class="line">	 <span class="comment">//  省略部分代码......</span></span><br><span class="line">         String[] aliasesArray = StringUtils.toStringArray(aliases);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">new</span> BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> AbstractBeanDefinition <span class="title">parseBeanDefinitionElement</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		Element ele, String beanName, <span class="meta">@Nullable</span> BeanDefinition containingBean)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">this</span>.parseState.push(<span class="keyword">new</span> BeanEntry(beanName));</span><br><span class="line"></span><br><span class="line">	String className = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (ele.hasAttribute(CLASS_ATTRIBUTE)) &#123;</span><br><span class="line">		className = ele.getAttribute(CLASS_ATTRIBUTE).trim();</span><br><span class="line">	&#125;</span><br><span class="line">	String parent = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (ele.hasAttribute(PARENT_ATTRIBUTE)) &#123;</span><br><span class="line">		parent = ele.getAttribute(PARENT_ATTRIBUTE);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		AbstractBeanDefinition bd = createBeanDefinition(className, parent);</span><br><span class="line"></span><br><span class="line">		parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);</span><br><span class="line">		bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));</span><br><span class="line">		<span class="comment">//以下是解析Bean标签里面的元数据填充完 BeanDefinition</span></span><br><span class="line">		parseMetaElements(ele, bd);</span><br><span class="line">		parseLookupOverrideSubElements(ele, bd.getMethodOverrides());</span><br><span class="line">		parseReplacedMethodSubElements(ele, bd.getMethodOverrides());</span><br><span class="line"></span><br><span class="line">		parseConstructorArgElements(ele, bd);</span><br><span class="line">		parsePropertyElements(ele, bd);</span><br><span class="line">		parseQualifierElements(ele, bd);</span><br><span class="line"></span><br><span class="line">		bd.setResource(<span class="keyword">this</span>.readerContext.getResource());</span><br><span class="line">		bd.setSource(extractSource(ele));</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> bd;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (ClassNotFoundException ex) &#123;</span><br><span class="line">		error(<span class="string">&quot;Bean class [&quot;</span> + className + <span class="string">&quot;] not found&quot;</span>, ele, ex); <span class="comment">//这个就是我们常见的错误</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (NoClassDefFoundError err) &#123;</span><br><span class="line">		error(<span class="string">&quot;Class that bean class [&quot;</span> + className + <span class="string">&quot;] depends on not found&quot;</span>, ele, err);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">		error(<span class="string">&quot;Unexpected failure during bean definition parsing&quot;</span>, ele, ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">		<span class="keyword">this</span>.parseState.pop();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> AbstractBeanDefinition <span class="title">createBeanDefinition</span><span class="params">(<span class="meta">@Nullable</span> String className, <span class="meta">@Nullable</span> String parentName)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> ClassNotFoundException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> BeanDefinitionReaderUtils.createBeanDefinition(</span><br><span class="line">			parentName, className, <span class="keyword">this</span>.readerContext.getBeanClassLoader());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="BeanDefinitionReaderUtils-createBeanDefinition"><a href="#BeanDefinitionReaderUtils-createBeanDefinition" class="headerlink" title="BeanDefinitionReaderUtils#createBeanDefinition()"></a>BeanDefinitionReaderUtils#createBeanDefinition()</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> AbstractBeanDefinition <span class="title">createBeanDefinition</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">      <span class="meta">@Nullable</span> String parentName, <span class="meta">@Nullable</span> String className, <span class="meta">@Nullable</span> ClassLoader classLoader)</span> <span class="keyword">throws</span> ClassNotFoundException </span>&#123;</span><br><span class="line"></span><br><span class="line">   GenericBeanDefinition bd = <span class="keyword">new</span> GenericBeanDefinition(); <span class="comment">//创建了一个BeanDefintion准备封装标签的内容</span></span><br><span class="line">   bd.setParentName(parentName);</span><br><span class="line">   <span class="keyword">if</span> (className != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (classLoader != <span class="keyword">null</span>) &#123;</span><br><span class="line">         bd.setBeanClass(ClassUtils.forName(className, classLoader));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         bd.setBeanClassName(className);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> bd;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>至此结束，上面的都不是很难，顺着调用栈就能看懂。</p>
</blockquote>
<h3 id="ApplicationContext接口功能"><a href="#ApplicationContext接口功能" class="headerlink" title="ApplicationContext接口功能"></a>ApplicationContext接口功能</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927175207106.png" />

<ol>
<li>ioc事件派发器</li>
<li>国际化解析</li>
<li>bean工厂功能—自动装配被组合进来的</li>
<li>资源解析功能</li>
<li>等等</li>
</ol>
<blockquote>
<p>这个就是我们常说的IOC容器</p>
</blockquote>
<h3 id="Aware接口功能分析"><a href="#Aware接口功能分析" class="headerlink" title="Aware接口功能分析"></a>Aware接口功能分析</h3><ol>
<li>aware中文翻译是<strong>意识到的，察觉到的，发现</strong>这么个意思。从翻译来看，aware做的事情应该是发现某一个东西。</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Marker superinterface indicating that a bean is eligible to be</span></span><br><span class="line"><span class="comment"> * notified by the Spring container of a particular framework object</span></span><br><span class="line"><span class="comment"> * through a callback-style method. Actual method signature is</span></span><br><span class="line"><span class="comment"> * determined by individual subinterfaces, but should typically</span></span><br><span class="line"><span class="comment"> * consist of just one void-returning method that accepts a single</span></span><br><span class="line"><span class="comment"> * argument.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Aware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>注释的大致意思是：Aware是一个标记性的超接口（顶级接口），指示了一个Bean有资格通过回调方法的形式获取Spring容器底层组件。实际回调方法被定义在每一个子接口中，而且通常一个子接口只包含一个接口一个参数并且返回值为void的方法。</li>
<li>说白了：只要实现了Aware子接口的Bean都能获取到一个Spring底层组件。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927191112023.png" />

<p>比如实现了ApplicationContextAware接口，实现它的方法，就能通过回调机制拿到ApplicationContext</p>
<h4 id="创建Person对象"><a href="#创建Person对象" class="headerlink" title="创建Person对象"></a>创建Person对象</h4><h5 id="流程图-Bean对象创建流程"><a href="#流程图-Bean对象创建流程" class="headerlink" title="流程图-Bean对象创建流程"></a>流程图-Bean对象创建流程</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.7/spring-sourcecode-v1/flow_chart/Spring%E6%BA%90%E7%A0%81-Bean%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA%E6%B5%81%E7%A8%8B.png">

<h5 id="Debug调用栈-2"><a href="#Debug调用栈-2" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><p>为了知道Aware的原理，我们给上面的pos_1和pos_2位置打上断点，看下是怎么进来的</p>
<p><strong>Person</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span>, <span class="title">MessageSourceAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   ApplicationContext context;  <span class="comment">//我们不用@Autowired也可以要到ioc容器</span></span><br><span class="line">   MessageSource messageSource;</span><br><span class="line">    </span><br><span class="line">   	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.name = name;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> name;</span><br><span class="line">	&#125; </span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span></span>&#123;</span><br><span class="line">	  System.out.println(<span class="string">&quot;person创建....&quot;</span>);  <span class="comment">//pos_1</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">//利用回调机制，把ioc容器传入</span></span><br><span class="line">      <span class="keyword">this</span>.context = applicationContext;  <span class="comment">//pos_2</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMessageSource</span><span class="params">(MessageSource messageSource)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.messageSource = messageSource;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>AnnotationMainTest</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 注解版Spring的用法</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">      ApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line">      Person bean = applicationContext.getBean(Person.class);</span><br><span class="line">      ApplicationContext context = bean.getContext();</span><br><span class="line"></span><br><span class="line">      System.out.println(context == applicationContext);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p><strong>MainConfig</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@ComponentScan(&quot;cn.imlql.spring&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span></span>&#123;</span><br><span class="line">      Person person = <span class="keyword">new</span> Person();</span><br><span class="line">      person.setName(<span class="string">&quot;李四&quot;</span>);</span><br><span class="line">      <span class="keyword">return</span> person;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927200211334.png" />

<ol>
<li>有一些一样的东西不再赘述</li>
<li>在<code>AbstractApplicationContext#refresh()</code>里会调用</li>
</ol>
<h5 id="AbstractApplicationContext-finishBeanFactoryInitialization-完成-BeanFactory-初始化"><a href="#AbstractApplicationContext-finishBeanFactoryInitialization-完成-BeanFactory-初始化" class="headerlink" title="AbstractApplicationContext#finishBeanFactoryInitialization()完成 BeanFactory 初始化"></a>AbstractApplicationContext#finishBeanFactoryInitialization()完成 BeanFactory 初始化</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">()</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">      <span class="keyword">synchronized</span> (<span class="keyword">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">         StartupStep contextRefresh = <span class="keyword">this</span>.applicationStartup.start(<span class="string">&quot;spring.context.refresh&quot;</span>);</span><br><span class="line"></span><br><span class="line">         <span class="comment">// BeanFactory第一次开始创建的时候,有xml解析逻辑。</span></span><br><span class="line">         ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();</span><br><span class="line">	 <span class="comment">// ...</span></span><br><span class="line">         <span class="keyword">try</span> &#123;                </span><br><span class="line">            <span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">            <span class="comment">//完成 BeanFactory 初始化</span></span><br><span class="line">            finishBeanFactoryInitialization(beanFactory);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finishBeanFactoryInitialization</span><span class="params">(ConfigurableListableBeanFactory beanFactory)</span> </span>&#123;</span><br><span class="line">	<span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">	<span class="comment">//初始化所有的单实例Bean</span></span><br><span class="line">	beanFactory.preInstantiateSingletons();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="DefaultListableBeanFactory-preInstantiateSingletons-循环遍历beanDefinitionName"><a href="#DefaultListableBeanFactory-preInstantiateSingletons-循环遍历beanDefinitionName" class="headerlink" title="DefaultListableBeanFactory#preInstantiateSingletons()循环遍历beanDefinitionName"></a>DefaultListableBeanFactory#preInstantiateSingletons()循环遍历beanDefinitionName</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">preInstantiateSingletons</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Pre-instantiating singletons in &quot;</span> + <span class="keyword">this</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   List&lt;String&gt; beanNames = <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="keyword">this</span>.beanDefinitionNames);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Trigger initialization of all non-lazy singleton beans...</span></span><br><span class="line">   <span class="keyword">for</span> (String beanName : beanNames) &#123;<span class="comment">//挨个遍历beanDefinitionName</span></span><br><span class="line">      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);</span><br><span class="line">      <span class="keyword">if</span> (!bd.isAbstract() &amp;&amp; bd.isSingleton() &amp;&amp; !bd.isLazyInit()) &#123;</span><br><span class="line">         <span class="keyword">if</span> (isFactoryBean(beanName)) &#123;</span><br><span class="line">            <span class="comment">// ...</span></span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span> &#123;</span><br><span class="line">            getBean(beanName);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="AbstractBeanFactory-getBean-准备获取Bean"><a href="#AbstractBeanFactory-getBean-准备获取Bean" class="headerlink" title="AbstractBeanFactory#getBean()准备获取Bean"></a>AbstractBeanFactory#getBean()准备获取Bean</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">getBean</span><span class="params">(String name)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> doGetBean(name, <span class="keyword">null</span>, <span class="keyword">null</span>, <span class="keyword">false</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">doGetBean</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">		String name, <span class="meta">@Nullable</span> Class&lt;T&gt; requiredType, <span class="meta">@Nullable</span> Object[] args, <span class="keyword">boolean</span> typeCheckOnly)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">	String beanName = transformedBeanName(name); <span class="comment">//转换Bean名字</span></span><br><span class="line">	Object beanInstance;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Eagerly check singleton cache for manually registered singletons.</span></span><br><span class="line">	Object sharedInstance = getSingleton(beanName); <span class="comment">//检查缓存中有没有</span></span><br><span class="line">	<span class="keyword">if</span> (sharedInstance != <span class="keyword">null</span> &amp;&amp; args == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="comment">//...</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="comment">//...</span></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			String[] dependsOn = mbd.getDependsOn();</span><br><span class="line">			<span class="keyword">if</span> (dependsOn != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">for</span> (String dep : dependsOn) &#123; <span class="comment">//看当前Bean有没有依赖其他Bean</span></span><br><span class="line"></span><br><span class="line">					<span class="keyword">try</span> &#123;</span><br><span class="line">						getBean(dep); <span class="comment">//依赖了其他bean，就先获取其他的哪些bean</span></span><br><span class="line">					&#125;</span><br><span class="line">					<span class="comment">//...</span></span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="comment">// Create bean instance. 创建bean的实例，下面是一个lamda表达式</span></span><br><span class="line">			<span class="keyword">if</span> (mbd.isSingleton()) &#123;</span><br><span class="line">				sharedInstance = getSingleton(beanName, () -&gt; &#123;</span><br><span class="line">					<span class="keyword">try</span> &#123;</span><br><span class="line">						<span class="keyword">return</span> createBean(beanName, mbd, args);  <span class="comment">//创建bean对象的实例</span></span><br><span class="line">					&#125;</span><br><span class="line">				&#125;);</span><br><span class="line">				beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);</span><br><span class="line">			&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> adaptBeanInstance(name, beanInstance, requiredType);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="DefaultSingletonBeanRegistry-getSingleton"><a href="#DefaultSingletonBeanRegistry-getSingleton" class="headerlink" title="DefaultSingletonBeanRegistry#getSingleton()"></a>DefaultSingletonBeanRegistry#getSingleton()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">getSingleton</span><span class="params">(String beanName, ObjectFactory&lt;?&gt; singletonFactory)</span> </span>&#123;</span><br><span class="line">   Assert.notNull(beanName, <span class="string">&quot;Bean name must not be null&quot;</span>);</span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>.singletonObjects) &#123;</span><br><span class="line">    	<span class="comment">// ...</span></span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 通过getObject获取真正的对象，有点类似于FactoryBean（这个不懂的建议先了解下Spring基本用法），</span></span><br><span class="line">            <span class="comment">// ObjectFactory类注释有说明。</span></span><br><span class="line">            singletonObject = singletonFactory.getObject();</span><br><span class="line">            newSingleton = <span class="keyword">true</span>;</span><br><span class="line">            <span class="comment">// ...</span></span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> singletonObject;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>下面就开始分析lamda表达式里的东西</p>
<h5 id="AbstractAutowireCapableBeanFactory-createBean"><a href="#AbstractAutowireCapableBeanFactory-createBean" class="headerlink" title="AbstractAutowireCapableBeanFactory#createBean()"></a>AbstractAutowireCapableBeanFactory#createBean()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">createBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line">   <span class="comment">//...</span></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         Object beanInstance = doCreateBean(beanName, mbdToUse, args);</span><br><span class="line">         <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(<span class="string">&quot;Finished creating instance of bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">return</span> beanInstance;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">       <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line">	<span class="comment">//...</span></span><br><span class="line">       <span class="keyword">if</span> (instanceWrapper == <span class="keyword">null</span>) &#123;</span><br><span class="line">           <span class="comment">//创建Bean的实例,默认使用无参构造器创建的对象</span></span><br><span class="line">           instanceWrapper = createBeanInstance(beanName, mbd, args);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> BeanWrapper <span class="title">createBeanInstance</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span> </span>&#123;</span><br><span class="line">       <span class="comment">//...</span></span><br><span class="line">       <span class="keyword">return</span> instantiateBean(beanName, mbd);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 指定Bean的创建策略；可以用jdk的反射，可以用cglib创建子类对象 Strategy for creating bean instances. */</span></span><br><span class="line"><span class="keyword">private</span> InstantiationStrategy instantiationStrategy;</span><br><span class="line"><span class="function"><span class="keyword">protected</span> BeanWrapper <span class="title">instantiateBean</span><span class="params">(String beanName, RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		Object beanInstance;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, <span class="keyword">this</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		BeanWrapper bw = <span class="keyword">new</span> BeanWrapperImpl(beanInstance);</span><br><span class="line">		initBeanWrapper(bw);</span><br><span class="line">		<span class="keyword">return</span> bw;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="SimpleInstantiationStrategy-instantiate-反射创建Bean"><a href="#SimpleInstantiationStrategy-instantiate-反射创建Bean" class="headerlink" title="SimpleInstantiationStrategy#instantiate()反射创建Bean"></a>SimpleInstantiationStrategy#instantiate()反射创建Bean</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">instantiate</span><span class="params">(RootBeanDefinition bd, <span class="meta">@Nullable</span> String beanName, BeanFactory owner)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// Don&#x27;t override the class with CGLIB if no overrides.</span></span><br><span class="line">   <span class="keyword">if</span> (!bd.hasMethodOverrides()) &#123;</span><br><span class="line">      <span class="keyword">return</span> BeanUtils.instantiateClass(constructorToUse);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h5 id="Spring内部的BeanUtils反射工具"><a href="#Spring内部的BeanUtils反射工具" class="headerlink" title="Spring内部的BeanUtils反射工具"></a>Spring内部的BeanUtils反射工具</h5><blockquote>
<p>这个类是Spring内部提供的反射工具类，平时项目你也可以用上，就不用自己写反射了</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> 	  <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">T <span class="title">instantiateClass</span><span class="params">(Constructor&lt;T&gt; ctor, Object... args)</span> <span class="keyword">throws</span> BeanInstantiationException </span>&#123;</span><br><span class="line">      Assert.notNull(ctor, <span class="string">&quot;Constructor must not be null&quot;</span>);</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         ReflectionUtils.makeAccessible(ctor);</span><br><span class="line">         <span class="keyword">else</span> &#123;        </span><br><span class="line">            Object[] argsWithDefaultValues = <span class="keyword">new</span> Object[args.length];        </span><br><span class="line">            <span class="keyword">return</span> ctor.newInstance(argsWithDefaultValues);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"><span class="comment">// 后面就是反射创建Person</span></span><br></pre></td></tr></table></figure>



<h4 id="Aware回调原理"><a href="#Aware回调原理" class="headerlink" title="Aware回调原理"></a>Aware回调原理</h4><h5 id="Debug调用栈-3"><a href="#Debug调用栈-3" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h5><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210927230734973.png"/>



<p>前面有很多一样的调用链，不再赘述。从doCreateBean:602调用栈开始不一样</p>
<h5 id="AbstractAutowireCapableBeanFactory-doCreateBean"><a href="#AbstractAutowireCapableBeanFactory-doCreateBean" class="headerlink" title="AbstractAutowireCapableBeanFactory#doCreateBean()"></a>AbstractAutowireCapableBeanFactory#doCreateBean()</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// Initialize the bean instance.</span></span><br><span class="line">      Object exposedObject = bean;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         populateBean(beanName, mbd, instanceWrapper);</span><br><span class="line">         exposedObject = initializeBean(beanName, exposedObject, mbd);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">initializeBean</span><span class="params">(String beanName, Object bean, <span class="meta">@Nullable</span> RootBeanDefinition mbd)</span> </span>&#123;</span><br><span class="line">	Object wrappedBean = bean;</span><br><span class="line">	<span class="keyword">if</span> (mbd == <span class="keyword">null</span> || !mbd.isSynthetic()) &#123;</span><br><span class="line">		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> wrappedBean;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">applyBeanPostProcessorsBeforeInitialization</span><span class="params">(Object existingBean, String beanName)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"></span><br><span class="line">	Object result = existingBean;</span><br><span class="line">	<span class="keyword">for</span> (BeanPostProcessor processor : getBeanPostProcessors()) &#123;</span><br><span class="line">		Object current = processor.postProcessBeforeInitialization(result, beanName);</span><br><span class="line">		<span class="keyword">if</span> (current == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line">		result = current;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ApplicationContextAwareProcessor"><a href="#ApplicationContextAwareProcessor" class="headerlink" title="ApplicationContextAwareProcessor"></a>ApplicationContextAwareProcessor</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!(bean <span class="keyword">instanceof</span> EnvironmentAware || bean <span class="keyword">instanceof</span> EmbeddedValueResolverAware ||</span><br><span class="line">            bean <span class="keyword">instanceof</span> ResourceLoaderAware || bean <span class="keyword">instanceof</span> ApplicationEventPublisherAware ||</span><br><span class="line">            bean <span class="keyword">instanceof</span> MessageSourceAware || bean <span class="keyword">instanceof</span> ApplicationContextAware ||</span><br><span class="line">            bean <span class="keyword">instanceof</span> ApplicationStartupAware)) &#123;</span><br><span class="line">         <span class="keyword">return</span> bean;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//...</span></span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         invokeAwareInterfaces(bean); <span class="comment">//执行aware接口规定的方法</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//就是在这里执行Aware回调</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">invokeAwareInterfaces</span><span class="params">(Object bean)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> EnvironmentAware) &#123;</span><br><span class="line">		((EnvironmentAware) bean).setEnvironment(<span class="keyword">this</span>.applicationContext.getEnvironment());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> EmbeddedValueResolverAware) &#123;</span><br><span class="line">		((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(<span class="keyword">this</span>.embeddedValueResolver);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> ResourceLoaderAware) &#123;</span><br><span class="line">		((ResourceLoaderAware) bean).setResourceLoader(<span class="keyword">this</span>.applicationContext);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> ApplicationEventPublisherAware) &#123;</span><br><span class="line">		((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(<span class="keyword">this</span>.applicationContext);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> MessageSourceAware) &#123;</span><br><span class="line">		((MessageSourceAware) bean).setMessageSource(<span class="keyword">this</span>.applicationContext);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> ApplicationStartupAware) &#123;</span><br><span class="line">		((ApplicationStartupAware) bean).setApplicationStartup(<span class="keyword">this</span>.applicationContext.getApplicationStartup());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (bean <span class="keyword">instanceof</span> ApplicationContextAware) &#123;</span><br><span class="line">		((ApplicationContextAware) bean).setApplicationContext(<span class="keyword">this</span>.applicationContext);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h2 id="属性赋值的时机（XML版）"><a href="#属性赋值的时机（XML版）" class="headerlink" title="属性赋值的时机（XML版）"></a>属性赋值的时机（XML版）</h2><h3 id="Debug调用栈-4"><a href="#Debug调用栈-4" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><p><strong>Person</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span>, <span class="title">MessageSourceAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   ApplicationContext context;  <span class="comment">//我们不用@Autowired也可以要到ioc容器</span></span><br><span class="line">   MessageSource messageSource;</span><br><span class="line">    </span><br><span class="line">   	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.name = name;  <span class="comment">// pos_2</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> name;</span><br><span class="line">	&#125; </span><br><span class="line">    </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span></span>&#123;</span><br><span class="line">	  System.out.println(<span class="string">&quot;person创建....&quot;</span>);  <span class="comment">//pos_1</span></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">//利用回调机制，把ioc容器传入</span></span><br><span class="line">      <span class="keyword">this</span>.context = applicationContext;  </span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMessageSource</span><span class="params">(MessageSource messageSource)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.messageSource = messageSource;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>MainTest</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		ClassPathXmlApplicationContext context = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;beans.xml&quot;</span>);</span><br><span class="line">		Person bean = context.getBean(Person.class);</span><br><span class="line">		System.out.println(bean);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>beans.xml</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">	   <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">	   <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;cn.imlql.spring.bean.Person&quot;</span> <span class="attr">id</span>=<span class="string">&quot;person&quot;</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;name&quot;</span> <span class="attr">value</span>=<span class="string">&quot;张三&quot;</span>/&gt;</span></span><br><span class="line"> 	<span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p>为了知道属性赋值的时机，这里要给setXXX方法打断点，也就是上面的pos_1和pos_2位置打断点。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928113235852.png" />



<p>还是老规矩，一样的就不说了，从调用栈不一样的地方开始说起。多看几遍，看到后面就会发现思路越来越清晰了。</p>
<h3 id="AbstractAutowireCapableBeanFactory-doCreateBean-1"><a href="#AbstractAutowireCapableBeanFactory-doCreateBean-1" class="headerlink" title="AbstractAutowireCapableBeanFactory#doCreateBean()"></a>AbstractAutowireCapableBeanFactory#doCreateBean()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">doCreateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> Object[] args)</span></span></span><br><span class="line"><span class="function">		<span class="keyword">throws</span> BeanCreationException </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Instantiate the bean.  这里面封装好了真正的Person对象</span></span><br><span class="line">	BeanWrapper instanceWrapper = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">if</span> (mbd.isSingleton()) &#123;</span><br><span class="line">		instanceWrapper = <span class="keyword">this</span>.factoryBeanInstanceCache.remove(beanName);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> (instanceWrapper == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="comment">//创建Bean的实例,默认使用无参构造器创建的对象</span></span><br><span class="line">		instanceWrapper = createBeanInstance(beanName, mbd, args);</span><br><span class="line">	&#125;</span><br><span class="line">       </span><br><span class="line">	<span class="comment">//......</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// Initialize the bean instance.</span></span><br><span class="line">	Object exposedObject = bean;</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		populateBean(beanName, mbd, instanceWrapper); <span class="comment">//给创建好的对象每个属性进行赋值</span></span><br><span class="line">		exposedObject = initializeBean(beanName, exposedObject, mbd);<span class="comment">//初始化bean</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> exposedObject;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>我们看到此时，Person的name属性还是null</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928114746618.png" />



<h3 id="AbstractAutowireCapableBeanFactory-populateBean-属性赋值"><a href="#AbstractAutowireCapableBeanFactory-populateBean-属性赋值" class="headerlink" title="AbstractAutowireCapableBeanFactory#populateBean()属性赋值"></a>AbstractAutowireCapableBeanFactory#populateBean()属性赋值</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">populateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> BeanWrapper bw)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这一步就是拿到属性值</span></span><br><span class="line">    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : <span class="keyword">null</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// ......      </span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pvs != <span class="keyword">null</span>) &#123;</span><br><span class="line">        applyPropertyValues(beanName, mbd, bw, pvs); <span class="comment">//xml版的所有配置会来到这里给属性赋值</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这里拿到属性值</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928115110820.png" />



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">applyPropertyValues</span><span class="params">(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ......</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Set our (possibly massaged) deep copy.</span></span><br><span class="line">    <span class="keyword">try</span> &#123; <span class="comment">//深拷贝所有PropertyValue应该对应的属性</span></span><br><span class="line">        bw.setPropertyValues(<span class="keyword">new</span> MutablePropertyValues(deepCopy));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928115352416.png"/>



<p>bw就是上面说的 =&gt; 里面封装好了真正的Person对象</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928115702735.png"/>







<p>这里就是一层一层调，不重要跳过。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928120016581.png" />



<h3 id="AbstractNestablePropertyAccessor-processLocalProperty"><a href="#AbstractNestablePropertyAccessor-processLocalProperty" class="headerlink" title="AbstractNestablePropertyAccessor#processLocalProperty"></a>AbstractNestablePropertyAccessor#processLocalProperty</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">processLocalProperty</span><span class="params">(PropertyTokenHolder tokens, PropertyValue pv)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// ...</span></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			Object originalValue = pv.getValue();</span><br><span class="line">			Object valueToApply = originalValue;</span><br><span class="line">			ph.setValue(valueToApply);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">//...</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928141536440.png"/>





<h3 id="BeanWrapperImpl内部类BeanPropertyHandler-setValue"><a href="#BeanWrapperImpl内部类BeanPropertyHandler-setValue" class="headerlink" title="BeanWrapperImpl内部类BeanPropertyHandler#setValue()"></a>BeanWrapperImpl内部类BeanPropertyHandler#setValue()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanPropertyHandler</span> <span class="keyword">extends</span> <span class="title">PropertyHandler</span> </span>&#123; </span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setValue</span><span class="params">(<span class="meta">@Nullable</span> Object value)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">       Method writeMethod = (<span class="keyword">this</span>.pd <span class="keyword">instanceof</span> GenericTypeAwarePropertyDescriptor ?</span><br><span class="line">             ((GenericTypeAwarePropertyDescriptor) <span class="keyword">this</span>.pd).getWriteMethodForActualAccess() :</span><br><span class="line">             <span class="keyword">this</span>.pd.getWriteMethod());</span><br><span class="line">       <span class="keyword">if</span> (System.getSecurityManager() != <span class="keyword">null</span>) &#123;</span><br><span class="line">          AccessController.doPrivileged((PrivilegedAction&lt;Object&gt;) () -&gt; &#123;</span><br><span class="line">             ReflectionUtils.makeAccessible(writeMethod);</span><br><span class="line">             <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">          &#125;);</span><br><span class="line">          <span class="keyword">try</span> &#123;</span><br><span class="line">             AccessController.doPrivileged((PrivilegedExceptionAction&lt;Object&gt;)</span><br><span class="line">                   () -&gt; writeMethod.invoke(getWrappedInstance(), value), acc);</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">catch</span> (PrivilegedActionException ex) &#123;</span><br><span class="line">             <span class="keyword">throw</span> ex.getException();</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">else</span> &#123;</span><br><span class="line">          ReflectionUtils.makeAccessible(writeMethod);</span><br><span class="line">           <span class="comment">// 这里的意思就是找到这个属性的写方法，所谓写方法就是setxxx方法</span></span><br><span class="line">          writeMethod.invoke(getWrappedInstance(), value);</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928143301161.png"/>

<p>最后就是反射走到了我们的<code>Person#setName(String name)</code></p>
<h3 id="再来看看messageSource何时赋值"><a href="#再来看看messageSource何时赋值" class="headerlink" title="再来看看messageSource何时赋值"></a>再来看看messageSource何时赋值</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928143910461.png"  />



<p>剩下的在上面的Aware回调原理讲过</p>
<h2 id="属性赋值的时机（注解版）"><a href="#属性赋值的时机（注解版）" class="headerlink" title="属性赋值的时机（注解版）"></a>属性赋值的时机（注解版）</h2><h3 id="Debug调用栈-5"><a href="#Debug调用栈-5" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><p><strong>AnnotationMainTest</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AnnotationMainTest</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      ApplicationContext applicationContext =</span><br><span class="line">            <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig.class);</span><br><span class="line"></span><br><span class="line">      Person bean = applicationContext.getBean(Person.class);</span><br><span class="line">      ApplicationContext context = bean.getContext();</span><br><span class="line">      System.out.println(context == applicationContext);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Cat</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;cat被创建了...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="meta">@Value(&quot;$&#123;JAVA_HOME&#125;&quot;)</span> <span class="comment">//自动赋值功能</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;cat....setName正在赋值调用....&quot;</span>);</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> name;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>MainConfig</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@ComponentScan(&quot;cn.imlql.spring&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">MainConfig</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;MainConfig...创建了....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span></span>&#123;</span><br><span class="line">      Person person = <span class="keyword">new</span> Person();</span><br><span class="line">      person.setName(<span class="string">&quot;李四&quot;</span>);</span><br><span class="line">      <span class="keyword">return</span> person;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>Person</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span>, <span class="title">MessageSourceAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   ApplicationContext context;  <span class="comment">//可以要到ioc容器  </span></span><br><span class="line">   </span><br><span class="line">   MessageSource messageSource;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> String name;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> Cat cat;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;person创建....&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> name;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="meta">@Autowired</span>  <span class="comment">//去发现一下.....</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCat</span><span class="params">(Cat cat)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.cat = cat;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Cat <span class="title">getCat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> cat;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;Person&#123;&quot;</span> +</span><br><span class="line">            <span class="string">&quot;name=&#x27;&quot;</span> + name + <span class="string">&#x27;\&#x27;&#x27;</span> +</span><br><span class="line">            <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> ApplicationContext <span class="title">getContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> context;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">//利用回调机制，把ioc容器传入</span></span><br><span class="line">      <span class="keyword">this</span>.context = applicationContext;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMessageSource</span><span class="params">(MessageSource messageSource)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.messageSource = messageSource;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>老样子，只看不一样的调用栈</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928151825366.png"/>

<h3 id="AbstractAutowireCapableBeanFactory-populateBean"><a href="#AbstractAutowireCapableBeanFactory-populateBean" class="headerlink" title="AbstractAutowireCapableBeanFactory#populateBean()"></a>AbstractAutowireCapableBeanFactory#populateBean()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">populateBean</span><span class="params">(String beanName, RootBeanDefinition mbd, <span class="meta">@Nullable</span> BeanWrapper bw)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// ......</span></span><br><span class="line">   PropertyDescriptor[] filteredPds = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (hasInstAwareBpps) &#123;</span><br><span class="line">      <span class="keyword">if</span> (pvs == <span class="keyword">null</span>) &#123;</span><br><span class="line">         pvs = mbd.getPropertyValues();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">for</span> (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) &#123;</span><br><span class="line">         <span class="comment">// 注解版的属性赋值会走这里</span></span><br><span class="line">         PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);</span><br><span class="line">         <span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (filteredPds == <span class="keyword">null</span>) &#123;</span><br><span class="line">               filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">            &#125;</span><br><span class="line">            pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);</span><br><span class="line">            <span class="keyword">if</span> (pvsToUse == <span class="keyword">null</span>) &#123;</span><br><span class="line">               <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         pvs = pvsToUse;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">if</span> (needsDepCheck) &#123;</span><br><span class="line">      <span class="keyword">if</span> (filteredPds == <span class="keyword">null</span>) &#123;</span><br><span class="line">         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);</span><br><span class="line">      &#125;</span><br><span class="line">      checkDependencies(beanName, mbd, filteredPds, pvs);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (pvs != <span class="keyword">null</span>) &#123;</span><br><span class="line">      applyPropertyValues(beanName, mbd, bw, pvs); <span class="comment">//xml版的所有配置会来到这里给属性赋值</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里有一个非常著名的后置处理器，<code>AutowiredAnnotationBeanPostProcessor</code>自动装配注解后置处理器，顾名思义就是用来处理@Autowired注解自动装配的。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_01/image-20210928153428691.png" />





<h3 id="AutowiredAnnotationBeanPostProcessor-postProcessProperties"><a href="#AutowiredAnnotationBeanPostProcessor-postProcessProperties" class="headerlink" title="AutowiredAnnotationBeanPostProcessor#postProcessProperties()"></a>AutowiredAnnotationBeanPostProcessor#postProcessProperties()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> PropertyValues <span class="title">postProcessProperties</span><span class="params">(PropertyValues pvs, Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);<span class="comment">//找到自动装配的元信息</span></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      metadata.inject(bean, beanName, pvs);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (BeanCreationException ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> ex;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> BeanCreationException(beanName, <span class="string">&quot;Injection of autowired dependencies failed&quot;</span>, ex);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> pvs;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<blockquote>
<p>下面的代码不在debug调用栈里，但是也比较重要</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="function"><span class="keyword">private</span> InjectionMetadata <span class="title">findAutowiringMetadata</span><span class="params">(String beanName, Class&lt;?&gt; clazz, <span class="meta">@Nullable</span> PropertyValues pvs)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// Fall back to class name as cache key, for backwards compatibility with custom callers.</span></span><br><span class="line">      String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());</span><br><span class="line">      <span class="comment">// Quick check on the concurrent map first, with minimal locking.</span></span><br><span class="line">      InjectionMetadata metadata = <span class="keyword">this</span>.injectionMetadataCache.get(cacheKey);</span><br><span class="line">      <span class="keyword">if</span> (InjectionMetadata.needsRefresh(metadata, clazz)) &#123;</span><br><span class="line">         <span class="keyword">synchronized</span> (<span class="keyword">this</span>.injectionMetadataCache) &#123;</span><br><span class="line">            metadata = <span class="keyword">this</span>.injectionMetadataCache.get(cacheKey);</span><br><span class="line">            <span class="keyword">if</span> (InjectionMetadata.needsRefresh(metadata, clazz)) &#123;</span><br><span class="line">               <span class="keyword">if</span> (metadata != <span class="keyword">null</span>) &#123;</span><br><span class="line">                  metadata.clear(pvs);</span><br><span class="line">               &#125;<span class="comment">//下面是分析当前类方法或者属性有没有标注@Autowired等自动赋值的注解</span></span><br><span class="line">               metadata = buildAutowiringMetadata(clazz);</span><br><span class="line">               <span class="keyword">this</span>.injectionMetadataCache.put(cacheKey, metadata);</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> metadata;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> InjectionMetadata <span class="title">buildAutowiringMetadata</span><span class="params">(<span class="keyword">final</span> Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (!AnnotationUtils.isCandidateClass(clazz, <span class="keyword">this</span>.autowiredAnnotationTypes)) &#123;</span><br><span class="line">		<span class="keyword">return</span> InjectionMetadata.EMPTY;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	List&lt;InjectionMetadata.InjectedElement&gt; elements = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">	Class&lt;?&gt; targetClass = clazz;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">do</span> &#123;</span><br><span class="line">		<span class="keyword">final</span> List&lt;InjectionMetadata.InjectedElement&gt; currElements = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">           <span class="comment">//找所有属性中标注了@Autowired\@Value\@Inject注解</span></span><br><span class="line">		ReflectionUtils.doWithLocalFields(targetClass, field -&gt; &#123;</span><br><span class="line">			MergedAnnotation&lt;?&gt; ann = findAutowiredAnnotation(field);</span><br><span class="line">			<span class="keyword">if</span> (ann != <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">if</span> (Modifier.isStatic(field.getModifiers())) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation is not supported on static fields: &quot;</span> + field);</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">boolean</span> required = determineRequiredStatus(ann);</span><br><span class="line">				currElements.add(<span class="keyword">new</span> AutowiredFieldElement(field, required));</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		<span class="comment">//拿到所有方法，看有没有@Autowired注解</span></span><br><span class="line">		ReflectionUtils.doWithLocalMethods(targetClass, method -&gt; &#123;</span><br><span class="line">			Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);</span><br><span class="line">			<span class="keyword">if</span> (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) &#123;</span><br><span class="line">				<span class="keyword">return</span>;</span><br><span class="line">			&#125;</span><br><span class="line">			MergedAnnotation&lt;?&gt; ann = findAutowiredAnnotation(bridgedMethod);</span><br><span class="line">			<span class="keyword">if</span> (ann != <span class="keyword">null</span> &amp;&amp; method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) &#123;</span><br><span class="line">				<span class="keyword">if</span> (Modifier.isStatic(method.getModifiers())) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation is not supported on static methods: &quot;</span> + method);</span><br><span class="line">					&#125;</span><br><span class="line">					<span class="keyword">return</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">if</span> (method.getParameterCount() == <span class="number">0</span>) &#123;</span><br><span class="line">					<span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">						logger.info(<span class="string">&quot;Autowired annotation should only be used on methods with parameters: &quot;</span> +</span><br><span class="line">								method);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">boolean</span> required = determineRequiredStatus(ann);</span><br><span class="line">				PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);</span><br><span class="line">				currElements.add(<span class="keyword">new</span> AutowiredMethodElement(method, required, pd));</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line"></span><br><span class="line">		elements.addAll(<span class="number">0</span>, currElements);</span><br><span class="line">		targetClass = targetClass.getSuperclass();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">while</span> (targetClass != <span class="keyword">null</span> &amp;&amp; targetClass != Object.class);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> InjectionMetadata.forElements(elements, clazz);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>BeanUtils：Bean反射工具类</p>
<p>ReflectionUtils：真正操作反射的工具类</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="meta">@Nullable</span></span><br><span class="line">   <span class="keyword">private</span> MergedAnnotation&lt;?&gt; findAutowiredAnnotation(AccessibleObject ao) &#123;</span><br><span class="line">      MergedAnnotations annotations = MergedAnnotations.from(ao);</span><br><span class="line">      <span class="keyword">for</span> (Class&lt;? extends Annotation&gt; type : <span class="keyword">this</span>.autowiredAnnotationTypes) &#123;</span><br><span class="line">         MergedAnnotation&lt;?&gt; annotation = annotations.get(type);</span><br><span class="line">         <span class="keyword">if</span> (annotation.isPresent()) &#123;</span><br><span class="line">            <span class="keyword">return</span> annotation;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Set&lt;Class&lt;? extends Annotation&gt;&gt; autowiredAnnotationTypes = <span class="keyword">new</span> LinkedHashSet&lt;&gt;(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AutowiredAnnotationBeanPostProcessor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">this</span>.autowiredAnnotationTypes.add(Autowired.class);</span><br><span class="line">	<span class="keyword">this</span>.autowiredAnnotationTypes.add(Value.class);</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="keyword">this</span>.autowiredAnnotationTypes.add((Class&lt;? extends Annotation&gt;)</span><br><span class="line">				ClassUtils.forName(<span class="string">&quot;javax.inject.Inject&quot;</span>, AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));</span><br><span class="line">		logger.trace(<span class="string">&quot;JSR-330 &#x27;javax.inject.Inject&#x27; annotation found and supported for autowiring&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (ClassNotFoundException ex) &#123;</span><br><span class="line">		<span class="comment">// JSR-330 API not available - simply skip.</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="InjectionMetadata-inject"><a href="#InjectionMetadata-inject" class="headerlink" title="InjectionMetadata#inject()"></a>InjectionMetadata#inject()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">inject</span><span class="params">(Object target, <span class="meta">@Nullable</span> String beanName, <span class="meta">@Nullable</span> PropertyValues pvs)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   Collection&lt;InjectedElement&gt; checkedElements = <span class="keyword">this</span>.checkedElements;</span><br><span class="line">   Collection&lt;InjectedElement&gt; elementsToIterate =</span><br><span class="line">         (checkedElements != <span class="keyword">null</span> ? checkedElements : <span class="keyword">this</span>.injectedElements);</span><br><span class="line">   <span class="keyword">if</span> (!elementsToIterate.isEmpty()) &#123;</span><br><span class="line">      <span class="keyword">for</span> (InjectedElement element : elementsToIterate) &#123;</span><br><span class="line">         element.inject(target, beanName, pvs);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="AutowiredAnnotationBeanPostProcessor内部类AutowiredMethodElement-inject"><a href="#AutowiredAnnotationBeanPostProcessor内部类AutowiredMethodElement-inject" class="headerlink" title="AutowiredAnnotationBeanPostProcessor内部类AutowiredMethodElement#inject()"></a>AutowiredAnnotationBeanPostProcessor内部类AutowiredMethodElement#inject()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">inject</span><span class="params">(Object bean, <span class="meta">@Nullable</span> String beanName, <span class="meta">@Nullable</span> PropertyValues pvs)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (checkPropertySkipping(pvs)) &#123;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   Method method = (Method) <span class="keyword">this</span>.member;</span><br><span class="line">   Object[] arguments;</span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.cached) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         arguments = resolveCachedArguments(beanName);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">         <span class="comment">// Unexpected removal of target bean for cached argument -&gt; re-resolve</span></span><br><span class="line">         arguments = resolveMethodArguments(method, bean, beanName);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      arguments = resolveMethodArguments(method, bean, beanName);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">if</span> (arguments != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         ReflectionUtils.makeAccessible(method);</span><br><span class="line">         method.invoke(bean, arguments);<span class="comment">// 这里就是反射调用setXXX了</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (InvocationTargetException ex) &#123;</span><br><span class="line">         <span class="keyword">throw</span> ex.getTargetException();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>BeanPostProcessor后置处理器贯穿整个Spring框架，Spring的事务，属性赋值，等等各方面都与其有着密不可分的关系，后面就开始讲BeanPostProcessor</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/599156d.html">https://imlql.cn/post/599156d.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/41fb8d9e.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div class="next-post pull-right"><a href="/post/1a003b7b.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring常用注解</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/6f2cef28.html" title="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-21</div><div class="title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BF%85%E8%AF%BB"><span class="toc-text">必读</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC1%E7%AB%A0-Spring%E6%BA%90%E7%A0%81%E7%BA%B5%E8%A7%88"><span class="toc-text">第1章-Spring源码纵览</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-text">概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB%E5%9B%BE"><span class="toc-text">简单的继承关系图</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E6%A1%86%E6%9E%B6%E6%95%B4%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-text">Spring框架整体流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6%E6%8E%A5%E5%8F%A3%E5%88%86%E6%9E%90"><span class="toc-text">核心组件接口分析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Resource%E8%B5%84%E6%BA%90"><span class="toc-text">Resource资源</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95"><span class="toc-text">方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-text">实现类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ResourceLoader%E8%B5%84%E6%BA%90%E5%8A%A0%E8%BD%BD%E5%99%A8"><span class="toc-text">ResourceLoader资源加载器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95-1"><span class="toc-text">方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E7%B1%BB-1"><span class="toc-text">实现类</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanFactory-Bean%E5%B7%A5%E5%8E%82"><span class="toc-text">BeanFactory-Bean工厂</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext"><span class="toc-text">AbstractApplicationContext</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#GenericApplicationContext"><span class="toc-text">GenericApplicationContext</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultListableBeanFactory"><span class="toc-text">DefaultListableBeanFactory</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E5%86%8CBeanDefinition-1"><span class="toc-text">注册BeanDefinition-1</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-BeanDefinition%E6%B3%A8%E5%86%8C%E6%B5%81%E7%A8%8B"><span class="toc-text">流程图-BeanDefinition注册流程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MainTest%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="toc-text">MainTest测试类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext-refresh-%E5%AE%B9%E5%99%A8%E5%88%B7%E6%96%B0"><span class="toc-text">AbstractApplicationContext#refresh()容器刷新</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractApplicationContext-obtainFreshBeanFactory-%E7%AC%AC%E4%B8%80%E6%AC%A1%E5%BC%80%E5%A7%8B%E5%88%9B%E5%BB%BABeanFactory"><span class="toc-text">AbstractApplicationContext#obtainFreshBeanFactory()第一次开始创建BeanFactory</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractRefreshableApplicationContext-refreshBeanFactory-%E5%88%B7%E6%96%B0%E6%95%B4%E4%B8%AABeanFactory"><span class="toc-text">AbstractRefreshableApplicationContext#refreshBeanFactory()刷新整个BeanFactory</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractXmlApplicationContext-loadBeanDefinitions-%E5%8A%A0%E8%BD%BDBean%E5%AE%9A%E4%B9%89%E4%BF%A1%E6%81%AF"><span class="toc-text">AbstractXmlApplicationContext#loadBeanDefinitions()加载Bean定义信息</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#AbstractBeanDefinitionReader-loadBeanDefinitions"><span class="toc-text">AbstractBeanDefinitionReader#loadBeanDefinitions()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#XmlBeanDefinitionReader-loadBeanDefinitions"><span class="toc-text">XmlBeanDefinitionReader#loadBeanDefinitions()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultBeanDefinitionDocumentReader-registerBeanDefinitions-%E6%B3%A8%E5%86%8CBean%E5%AE%9A%E4%B9%89%E4%BF%A1%E6%81%AF"><span class="toc-text">DefaultBeanDefinitionDocumentReader#registerBeanDefinitions()注册Bean定义信息</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanDefinitionReaderUtils-registerBeanDefinition"><span class="toc-text">BeanDefinitionReaderUtils#registerBeanDefinition()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultListableBeanFactory-registerBeanDefinition"><span class="toc-text">DefaultListableBeanFactory#registerBeanDefinition()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E5%86%8CBeanDefinition-2"><span class="toc-text">注册BeanDefinition-2</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-1"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#DefaultBeanDefinitionDocumentReader-processBeanDefinition"><span class="toc-text">DefaultBeanDefinitionDocumentReader#processBeanDefinition()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanDefinitionParserDelegate-parseBeanDefinitionElement"><span class="toc-text">BeanDefinitionParserDelegate#parseBeanDefinitionElement()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanDefinitionReaderUtils-createBeanDefinition"><span class="toc-text">BeanDefinitionReaderUtils#createBeanDefinition()</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ApplicationContext%E6%8E%A5%E5%8F%A3%E5%8A%9F%E8%83%BD"><span class="toc-text">ApplicationContext接口功能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Aware%E6%8E%A5%E5%8F%A3%E5%8A%9F%E8%83%BD%E5%88%86%E6%9E%90"><span class="toc-text">Aware接口功能分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BAPerson%E5%AF%B9%E8%B1%A1"><span class="toc-text">创建Person对象</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E5%9B%BE-Bean%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA%E6%B5%81%E7%A8%8B"><span class="toc-text">流程图-Bean对象创建流程</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-2"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractApplicationContext-finishBeanFactoryInitialization-%E5%AE%8C%E6%88%90-BeanFactory-%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">AbstractApplicationContext#finishBeanFactoryInitialization()完成 BeanFactory 初始化</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#DefaultListableBeanFactory-preInstantiateSingletons-%E5%BE%AA%E7%8E%AF%E9%81%8D%E5%8E%86beanDefinitionName"><span class="toc-text">DefaultListableBeanFactory#preInstantiateSingletons()循环遍历beanDefinitionName</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractBeanFactory-getBean-%E5%87%86%E5%A4%87%E8%8E%B7%E5%8F%96Bean"><span class="toc-text">AbstractBeanFactory#getBean()准备获取Bean</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#DefaultSingletonBeanRegistry-getSingleton"><span class="toc-text">DefaultSingletonBeanRegistry#getSingleton()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-createBean"><span class="toc-text">AbstractAutowireCapableBeanFactory#createBean()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#SimpleInstantiationStrategy-instantiate-%E5%8F%8D%E5%B0%84%E5%88%9B%E5%BB%BABean"><span class="toc-text">SimpleInstantiationStrategy#instantiate()反射创建Bean</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Spring%E5%86%85%E9%83%A8%E7%9A%84BeanUtils%E5%8F%8D%E5%B0%84%E5%B7%A5%E5%85%B7"><span class="toc-text">Spring内部的BeanUtils反射工具</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Aware%E5%9B%9E%E8%B0%83%E5%8E%9F%E7%90%86"><span class="toc-text">Aware回调原理</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-3"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-doCreateBean"><span class="toc-text">AbstractAutowireCapableBeanFactory#doCreateBean()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ApplicationContextAwareProcessor"><span class="toc-text">ApplicationContextAwareProcessor</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC%E7%9A%84%E6%97%B6%E6%9C%BA%EF%BC%88XML%E7%89%88%EF%BC%89"><span class="toc-text">属性赋值的时机（XML版）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-4"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-doCreateBean-1"><span class="toc-text">AbstractAutowireCapableBeanFactory#doCreateBean()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-populateBean-%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC"><span class="toc-text">AbstractAutowireCapableBeanFactory#populateBean()属性赋值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractNestablePropertyAccessor-processLocalProperty"><span class="toc-text">AbstractNestablePropertyAccessor#processLocalProperty</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#BeanWrapperImpl%E5%86%85%E9%83%A8%E7%B1%BBBeanPropertyHandler-setValue"><span class="toc-text">BeanWrapperImpl内部类BeanPropertyHandler#setValue()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%8D%E6%9D%A5%E7%9C%8B%E7%9C%8BmessageSource%E4%BD%95%E6%97%B6%E8%B5%8B%E5%80%BC"><span class="toc-text">再来看看messageSource何时赋值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC%E7%9A%84%E6%97%B6%E6%9C%BA%EF%BC%88%E6%B3%A8%E8%A7%A3%E7%89%88%EF%BC%89"><span class="toc-text">属性赋值的时机（注解版）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-5"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractAutowireCapableBeanFactory-populateBean"><span class="toc-text">AbstractAutowireCapableBeanFactory#populateBean()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AutowiredAnnotationBeanPostProcessor-postProcessProperties"><span class="toc-text">AutowiredAnnotationBeanPostProcessor#postProcessProperties()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#InjectionMetadata-inject"><span class="toc-text">InjectionMetadata#inject()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AutowiredAnnotationBeanPostProcessor%E5%86%85%E9%83%A8%E7%B1%BBAutowiredMethodElement-inject"><span class="toc-text">AutowiredAnnotationBeanPostProcessor内部类AutowiredMethodElement#inject()</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>